

from jsonschema import validate
from sanic import Blueprint, Request,json as jsonResp

from app.core.entity import ApiResult
from app.service.projectDetails import ProjectDetailsService
from app.utils.RequestUtils import RequestUtils


bp=Blueprint("projectDetails",url_prefix="/project/details")

addProjectSchema={
    "type":"object",
    "properties":{
        "title":{"type":"string"},
        "payDate":{"type":"string",format:"date"},
        "payGroupId":{"type":"number"},
        "price":{"type":"number"},
        "remark":{"type":"string"},
        "payer":{"type":"number"}
    },
    "required":["title","payDate","payGroupId","price","payer"]
}

@bp.route('/add',methods=['POST'])
async def projectAdd(request:Request):
    postData=request.load_json()
    if postData==None:
        postData={}
    validate(instance=postData,schema=addProjectSchema)
    postData["price"]=float(postData["price"])
    postData["payer"]=int(postData["payer"])
    postData['createdBy']=RequestUtils().getCurrentUserId()
    ProjectDetailsService.createProjectDetails(postData,RequestUtils().getCurrentProjectId())
    return jsonResp(vars(ApiResult.success()))

@bp.route('/upd/<id>',methods=['POST'])
async def projectUpd(request:Request,id:int):
    postData=request.load_json()
    if postData==None:
        postData={}
    validate(instance=postData,schema=addProjectSchema)
    postData["price"]=float(postData["price"])
    postData["id"]=id
    ProjectDetailsService.updateProjectDetails(postData)
    return jsonResp(vars(ApiResult.success()))

@bp.route('/del/<id>',methods=['POST'])
async def projectDelete(request:Request,id:int):
    ProjectDetailsService.deleteProjectDetails(id)
    return jsonResp(vars(ApiResult.success(msg="删除成功")))

@bp.route('/get/<id>',methods=['GET'])
async def projectGet(request:Request,id:int):
    pd=ProjectDetailsService.existsProjectDetail(id)
    data=pd.toJson()
    data['payer_desc']=pd.getPayerDescAttr()
    data['payGroupId_desc']=pd.getPayGroupDescAttr()
    return jsonResp(vars(ApiResult.success(data=data)))

@bp.route('/list',methods=['GET'])
async def projectList(request:Request):
    postData=request.load_json()
    if postData==None:
        postData={}
    pdList=ProjectDetailsService.listProjectDetails(RequestUtils().getCurrentProjectId(),postData)
    respList=[]
    for pd in pdList:
        obj=pd.toJson()
        obj['payer_desc']=pd.getPayerDescAttr()
        obj['payGroupId_desc']=pd.getPayGroupDescAttr()
        respList.append(obj)
    return jsonResp(vars(ApiResult.success(data={"list":respList})))